#!/usr/bin/env python
import os
import hmac
import time
import hashlib
import urllib2
import datetime
from urllib import urlencode
try:
    import simplejson
    HAS_JSON = True
except ImportError:
    HAS_JSON = False
try:
    if not HAS_JSON:
        from django.utils import simplejson
    from django.core.management import setup_environ
    import settings
    setup_environ(settings)
    try:
        """
        Settings for if you are running this within a django-fied site
        """
        DOWNLOAD_DIRECTORY = settings.GAME_DOWNLOAD_DIRECTORY
        HAS_JSON = True
    except AttributeError:
        DOWNLOAD_DIRECTORY = os.path.join(settings.MEDIA_ROOT, "django-arcade")
    SECRET_KEY = settings.SECRET_KEY
except ImportError:
    """
    Set download directory here since you are not running under django
    """
    DOWNLOAD_DIRECTORY = None
    SECRET_KEY = None # Put your django site's secret key here if you're not running cron under your django site!!!!

DJANGO_ARCADE_SERVICE = "http://localhost:8000/games/service"

def get_queued_games():
    f = urllib2.urlopen("%s/q" % DJANGO_ARCADE_SERVICE)
    q_json = f.read()
    q_data = simplejson.loads(q_json)
    return q_data

def notify_service(downloaded_games):
    url = "%s/u" % DJANGO_ARCADE_SERVICE
    values = dict(
        games=downloaded_games
        key=hmac.new(SECRET_KEY, '\n'.join(downloaded_games), hashlib.sha256)
    )
    val_json = simplejson.dumps(values)
    

def process_queue():
    downloaded_games = []
    if HAS_JSON:
        q_data = get_queued_games()
        for q in g_data.get('download', []):
            game_url = urllib2.urlopen(q.swf_url)
            game_file = os.path.join(DOWNLOAD_DIRECTORY, q.slug, "%s.swf" % q.slug)
            game_fp = open(game_file, "wb")
            game_fp.write(game_url.read())
            game_fp.close()
            if os.path.exists(os.path.join(DOWNLOAD_DIRECTORY, q.slug, "%s.swf" % q.slug)):
                downloaded_games.append(q.slug)
        notify_service(downloaded_games)
        